<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单确认 - 商品管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .order-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .order-section {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        .address-item {
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .address-item:hover {
            border-color: #0d6efd;
        }
        .address-item.selected {
            border-color: #0d6efd;
            background-color: rgba(13, 110, 253, 0.05);
        }
        .product-item {
            display: flex;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #e9ecef;
        }
        .product-item:last-child {
            border-bottom: none;
        }
        .product-image {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 4px;
            margin-right: 15px;
        }
        .product-info {
            flex: 1;
        }
        .product-price {
            color: #dc3545;
            font-weight: bold;
        }
        .order-summary {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
        }
        .payment-method {
            margin-bottom: 10px;
        }
        .payment-method input[type="radio"] {
            margin-right: 8px;
        }
        .submit-order-btn {
            width: 100%;
            padding: 12px;
            font-size: 16px;
            font-weight: bold;
        }
        .steps {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
        }
        .step {
            text-align: center;
            flex: 1;
            position: relative;
        }
        .step::after {
            content: '';
            position: absolute;
            top: 15px;
            right: -50%;
            width: 100%;
            height: 2px;
            background-color: #e9ecef;
            z-index: 1;
        }
        .step:last-child::after {
            display: none;
        }
        .step.active .step-icon {
            background-color: #0d6efd;
            color: white;
        }
        .step.active .step-text {
            color: #0d6efd;
        }
        .step-icon {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: #e9ecef;
            color: #6c757d;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 8px;
            position: relative;
            z-index: 2;
        }
        .step-text {
            font-size: 14px;
            color: #6c757d;
        }
        .new-address-btn {
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav th:replace="~{shop/fragments :: navbar}"></nav>
    
    <div class="order-container">
        <h2 class="mb-4">确认订单</h2>
        
        <!-- 步骤指示器 -->
        <div class="steps">
            <div class="step active">
                <div class="step-icon">1</div>
                <div class="step-text">确认订单信息</div>
            </div>
            <div class="step">
                <div class="step-icon">2</div>
                <div class="step-text">支付订单</div>
            </div>
            <div class="step">
                <div class="step-icon">3</div>
                <div class="step-text">支付成功</div>
            </div>
        </div>
        
        <!-- 收货地址 -->
        <div class="order-section">
            <h5 class="mb-3">收货地址</h5>
            
            <button class="btn btn-outline-primary new-address-btn" data-bs-toggle="modal" data-bs-target="#newAddressModal">
                <i class="bi bi-plus-circle"></i> 新增收货地址
            </button>
            
            <div class="address-list">
                <div th:if="${#lists.isEmpty(addresses)}" class="alert alert-warning">
                    您还没有添加收货地址，请先添加收货地址
                </div>
                
                <div th:each="address : ${addresses}" class="address-item" 
                     th:classappend="${address.isDefault} ? selected : ''"
                     th:data-address-id="${address.id}">
                    <div class="d-flex justify-content-between">
                        <div>
                            <div class="fw-bold" th:text="${address.name}">收货人</div>
                            <div th:text="${address.phone}">联系电话</div>
                            <div th:text="${address.province + ' ' + address.city + ' ' + address.district + ' ' + address.detail}">
                                收货地址
                            </div>
                        </div>
                        <div>
                            <span th:if="${address.isDefault}" class="badge bg-primary">默认地址</span>
                            <button class="btn btn-sm btn-outline-secondary edit-address-btn" 
                                    th:data-address-id="${address.id}">
                                编辑
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 商品清单 -->
        <div class="order-section">
            <h5 class="mb-3">商品清单</h5>
            
            <div th:each="item : ${cartItems}" class="product-item">
                <img th:src="${item.productImage}" alt="商品图片" class="product-image">
                <div class="product-info">
                    <div class="fw-bold" th:text="${item.productName}">商品名称</div>
                    <div class="text-muted small" th:text="${item.specification}">商品规格</div>
                    <div class="d-flex justify-content-between align-items-center mt-2">
                        <div>
                            <span class="text-muted">单价：</span>
                            <span class="product-price">¥<span th:text="${#numbers.formatDecimal(item.price, 1, 2)}">0.00</span></span>
                        </div>
                        <div>
                            <span class="text-muted">数量：</span>
                            <span th:text="${item.quantity}">1</span>
                        </div>
                        <div>
                            <span class="text-muted">小计：</span>
                            <span class="product-price">¥<span th:text="${#numbers.formatDecimal(item.subtotal, 1, 2)}">0.00</span></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 支付方式 -->
        <div class="order-section">
            <h5 class="mb-3">支付方式</h5>
            
            <div class="payment-method">
                <label>
                    <input type="radio" name="paymentMethod" value="alipay" checked>
                    <i class="bi bi-alipay"></i> 支付宝
                </label>
            </div>
            <div class="payment-method">
                <label>
                    <input type="radio" name="paymentMethod" value="wechat">
                    <i class="bi bi-wechat"></i> 微信支付
                </label>
            </div>
            <div class="payment-method">
                <label>
                    <input type="radio" name="paymentMethod" value="bank">
                    <i class="bi bi-credit-card"></i> 银行卡支付
                </label>
            </div>
        </div>
        
        <!-- 订单备注 -->
        <div class="order-section">
            <h5 class="mb-3">订单备注</h5>
            <textarea class="form-control" id="orderRemark" rows="3" placeholder="选填，请先和商家协商一致"></textarea>
        </div>
        
        <!-- 订单汇总 -->
        <div class="order-section">
            <div class="order-summary">
                <div class="d-flex justify-content-between mb-2">
                    <span>商品件数：</span>
                    <span th:text="${totalQuantity}">0</span>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span>商品总价：</span>
                    <span>¥<span th:text="${#numbers.formatDecimal(totalAmount, 1, 2)}">0.00</span></span>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span>运费：</span>
                    <span>¥0.00</span>
                </div>
                <hr>
                <div class="d-flex justify-content-between fw-bold">
                    <span>应付总额：</span>
                    <span class="text-danger">¥<span th:text="${#numbers.formatDecimal(totalAmount, 1, 2)}">0.00</span></span>
                </div>
            </div>
            
            <button class="btn btn-primary submit-order-btn mt-3" id="submitOrderBtn">
                提交订单
            </button>
        </div>
    </div>
    
    <!-- 新增地址模态框 -->
    <div class="modal fade" id="newAddressModal" tabindex="-1" aria-labelledby="newAddressModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="newAddressModalLabel">新增收货地址</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="newAddressForm">
                        <div class="mb-3">
                            <label for="name" class="form-label">收货人</label>
                            <input type="text" class="form-control" id="name" required>
                        </div>
                        <div class="mb-3">
                            <label for="phone" class="form-label">联系电话</label>
                            <input type="tel" class="form-control" id="phone" required>
                        </div>
                        <div class="mb-3">
                            <label for="province" class="form-label">省份</label>
                            <input type="text" class="form-control" id="province" required>
                        </div>
                        <div class="mb-3">
                            <label for="city" class="form-label">城市</label>
                            <input type="text" class="form-control" id="city" required>
                        </div>
                        <div class="mb-3">
                            <label for="district" class="form-label">区县</label>
                            <input type="text" class="form-control" id="district" required>
                        </div>
                        <div class="mb-3">
                            <label for="detail" class="form-label">详细地址</label>
                            <textarea class="form-control" id="detail" rows="2" required></textarea>
                        </div>
                        <div class="mb-3 form-check">
                            <input type="checkbox" class="form-check-input" id="isDefault">
                            <label class="form-check-label" for="isDefault">设为默认地址</label>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveAddressBtn">保存</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 页脚 -->
    <footer th:replace="~{shop/fragments :: footer}"></footer>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 选择收货地址
        document.querySelectorAll('.address-item').forEach(item => {
            item.addEventListener('click', function() {
                document.querySelectorAll('.address-item').forEach(i => i.classList.remove('selected'));
                this.classList.add('selected');
            });
        });
        
        // 提交订单
        document.getElementById('submitOrderBtn').addEventListener('click', function() {
            const selectedAddress = document.querySelector('.address-item.selected');
            if (!selectedAddress) {
                showToast('请选择收货地址', 'warning');
                return;
            }
            
            const addressId = selectedAddress.getAttribute('data-address-id');
            const paymentMethod = document.querySelector('input[name="paymentMethod"]:checked').value;
            const remark = document.getElementById('orderRemark').value;
            
            // 禁用按钮，防止重复提交
            this.disabled = true;
            this.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 提交中...';
            
            // 发送请求
            fetch('/order/submit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    addressId: addressId,
                    paymentMethod: paymentMethod,
                    remark: remark
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('订单提交成功', 'success');
                    // 跳转到支付页面
                    setTimeout(() => {
                        window.location.href = '/order/pay/' + data.orderId;
                    }, 1500);
                } else {
                    showToast(data.message, 'danger');
                    // 恢复按钮状态
                    this.disabled = false;
                    this.innerHTML = '提交订单';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('提交订单失败，请重试', 'danger');
                // 恢复按钮状态
                this.disabled = false;
                this.innerHTML = '提交订单';
            });
        });
        
        // 保存新地址
        document.getElementById('saveAddressBtn').addEventListener('click', function() {
            const form = document.getElementById('newAddressForm');
            const formData = new FormData(form);
            
            // 转换为URLSearchParams
            const params = new URLSearchParams();
            params.append('name', document.getElementById('name').value);
            params.append('phone', document.getElementById('phone').value);
            params.append('province', document.getElementById('province').value);
            params.append('city', document.getElementById('city').value);
            params.append('district', document.getElementById('district').value);
            params.append('detail', document.getElementById('detail').value);
            params.append('isDefault', document.getElementById('isDefault').checked);
            
            // 发送请求
            fetch('/address/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: params
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('地址添加成功', 'success');
                    // 关闭模态框
                    const modal = bootstrap.Modal.getInstance(document.getElementById('newAddressModal'));
                    modal.hide();
                    // 刷新页面
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                } else {
                    showToast(data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('添加地址失败，请重试', 'danger');
            });
        });
        
        // Toast提示函数
        function showToast(message, type = 'info') {
            // 创建toast容器（如果不存在）
            let toastContainer = document.getElementById('toastContainer');
            if (!toastContainer) {
                toastContainer = document.createElement('div');
                toastContainer.id = 'toastContainer';
                toastContainer.style.position = 'fixed';
                toastContainer.style.top = '20px';
                toastContainer.style.right = '20px';
                toastContainer.style.zIndex = '1050';
                document.body.appendChild(toastContainer);
            }
            
            // 创建toast元素
            const toast = document.createElement('div');
            toast.className = `toast align-items-center text-white bg-${type === 'danger' ? 'danger' : type === 'warning' ? 'warning' : type === 'success' ? 'success' : 'primary'}`;
            toast.setAttribute('role', 'alert');
            toast.setAttribute('aria-live', 'assertive');
            toast.setAttribute('aria-atomic', 'true');
            
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            `;
            
            // 添加到容器
            toastContainer.appendChild(toast);
            
            // 初始化toast
            const bsToast = new bootstrap.Toast(toast, {
                autohide: true,
                delay: 3000
            });
            
            // 显示toast
            bsToast.show();
            
            // 监听隐藏事件，移除元素
            toast.addEventListener('hidden.bs.toast', function() {
                toast.remove();
            });
        }
    </script>
</body>
</html>